package com.e9ab98e991ab.librepository.api;

import android.text.TextUtils;

import java.io.IOException;

import retrofit2.Response;

/**
 * 响应体
 * @author gaoxin 18-11-7 上午10:38
 * @version V1.0.0
 * @name ApiResponse
 */
public class ApiResponse<T> {
    /**
     * 错误返回
     * @param error Throwable
     * @param <T> T
     * @return ApiErrorResponse
     */
    public static <T> ApiErrorResponse<T> create(Throwable error) {
        return new ApiErrorResponse<>(TextUtils.isEmpty(error.getMessage()) ? "unknown error" : error.getMessage());
    }

    /**
     * Success 返回
     * @param response 响应
     * @param <T> t
     * @return X
     */
    public static <T> ApiResponse<T> create(Response<T> response) {
        if (response.isSuccessful()) {
            T body = response.body();
            if (body == null || response.code() == 204) {
                /***
                 * 空响应
                 */
                return new ApiEmptyResponse<>();
            } else {
                /***
                 * 可读取请求headers中的参数
                 */
                return new ApiSuccessResponse<>(body);
            }
        } else {
            String msg = "";
            if (response.errorBody() != null) {
                try {
                    msg = response.errorBody().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            String errorMsg = msg;
            if (TextUtils.isEmpty(msg)) {
                errorMsg = response.message();
            }
            return new ApiErrorResponse<>(TextUtils.isEmpty(errorMsg) ? "unknown error" : errorMsg);
        }
    }
}
